"use strict"

//imports
var fs			=	require('fs')

//variables
var log 		= 	console.log,
	myTimer		=	null,
	gamesFolder =	"stored-games/",
	movesFolder = 	"stored-moves/",
	mins		=	60*1000											//miliseconds in a minute

//start timer - every 1 minute, run a function which cleans all games stored locally
exports.start = function() {
	myTimer = setInterval(stage1, 2*mins)							//run once per minute
}

//stage 1 - get a list of all stored games
var stage1 = function() {
	fs.readdir(gamesFolder, stage2)
}

//stage 2 - read each file asynchronously to an array of json blobs
var stage2 = function(err, allFiles) {
	//get all .txt files out of the files array
	var files = [ ]
	for (var i=0; i<allFiles.length; i++) {
		if (allFiles[i].match( /.txt/ )) {
			files.push(allFiles[i])
		}
	}
	
	//check result of stage 1 for errors
	if (err) {
		log("stage2: " + err)
		return
	} else if (files.length === 0) {
		log("stage2: no games in the database to check")
		return
	}
		
	//some values to be inherited by the closure
	var currentTime = new Date().getTime(),
		oldGames = [ ],
		checkedGames = 0
	
	
	//this callback is run for every file
	var callback = function(err, data) {
		if (err) {												//error check
			log("stage2 callback: " + err)
			return
		}
		
		var data = JSON.parse(data)								//get as json
		if (data.lastUpdated + 2*mins < currentTime) {			//check if last move was > 2 minutes ago
			oldGames.push(data.gameId)							//if so, add to list of files to delete
		}
		
		checkedGames++
		if (checkedGames === files.length) {
			stage3(oldGames)
		}
	}
	
	
	//load each game asynchronously
	for (var i=0; i<files.length; i++) {
		fs.readFile( gamesFolder + files[i], 'utf8', callback )
	}
}


//stage3 - delete all games that are older that 5 minutes!
var stage3 = function(oldGames) {
	log("cleaner: deleting " + oldGames.length + " games")
	
	for (var i=0; i<oldGames.length; i++) {
		fs.unlink( gamesFolder + oldGames[i] + ".txt" )			//delete game
		fs.unlink( movesFolder + oldGames[i] + ".txt" )			//delete associated moves, if they exist
	}
}

